<template>
  <el-dialog
    top="5vh"
    :visible="showVisible"
    center
    :show-close="false"
    width="700px"
    :append-to-body="true"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "添加触发器" : "编辑触发器" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>
    <el-form
      class="pl30 pr30"
      :model="formData"
      ref="form"
      label-position="top"
    >
      <el-form-item
        label="触发器编码"
        prop="code"
        :rules="[
          { required: true, message: '触发器编码不能为空', trigger: 'change' },
          {
            pattern: COMMON_CODE_REG_64,
            message: '请输入有效的触发器编码',
            trigger: 'change',
          },
        ]"
      >
        <template slot="label"
          >触发器编码
          <el-tooltip
            popper-class="custom-popper"
            :content="COMMON_CODE_REG_64_MSG"
            placement="top"
          >
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-input
          :disabled="!isNew"
          v-model="formData.code"
          placeholder="请输入触发器编码"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="触发器名称"
        prop="name"
        :rules="[
          { required: true, message: '触发器名称不能为空', trigger: 'change' },
        ]"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入触发器名称"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
        :rules="[
          { required: true, message: '状态不能为空', trigger: 'change' },
        ]"
      >
        <el-select v-model="formData.status">
          <el-option
            v-for="item in RULE_STATUS_ENUM"
            :key="item.label"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="关联业务方法"
        prop="services"
        :rules="[
          {
            required: true,
            message: '关联业务方法不能为空',
            trigger: 'change',
          },
        ]"
      >
        <el-select
          multiple
          clearable
          style="width: 100%"
          v-model="formData.services"
          filterable
        >
          <el-option
            v-for="item in serviceList"
            :key="item.key"
            :value="item.key"
            :label="item.key + '(' + item.name + ')'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="触发器说明" prop="notes">
        <el-input
          type="textarea"
          style="width: 100%"
          :maxlength="200"
          v-model.trim="formData.notes"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="触发类型"
        prop="type"
        :rules="[
          { required: true, message: '触发类型不能为空', trigger: 'change' },
        ]"
      >
        <el-radio-group @change="changeType" v-model="formData.type">
          <el-radio-button label="WEBHOOK"></el-radio-button>
          <el-radio-button label="MQTT"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="formData.type === 'WEBHOOK' ? '回调地址' : 'TOPIC主题'"
        prop="configJson"
      >
        <el-row
          v-for="(config, index) in formData.configJson"
          :key="index"
          class="mb5"
          :gutter="8"
        >
          <el-col :span="2"
            ><div class="tc">{{ index + 1 }}</div></el-col
          >
          <el-col :span="9">
            <el-form-item
              :prop="'configJson.' + index + '.key'"
              :rules="{
                required: true,
                message:
                  formData.type === 'WEBHOOK'
                    ? '第三方服务不能为空'
                    : 'MQTT不能为空',
                trigger: 'change',
              }"
            >
              <el-select
                v-if="formData.type === 'WEBHOOK'"
                filterable
                clearable
                style="width: 100%"
                v-model="config.key"
                placeholder="请选择第三方服务"
              >
                <el-option
                  v-for="item in httpServiceList"
                  :key="item.key"
                  :value="item.key"
                  :label="item.name"
                />
              </el-select>
              <el-select
                v-else
                filterable
                clearable
                style="width: 100%"
                v-model="config.key"
                placeholder="请选择MQTT"
              >
                <el-option
                  v-for="item in mqttSelectList"
                  :key="item.key"
                  :value="item.key"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item
              :prop="'configJson.' + index + '.value'"
              :rules="[
                {
                  required: true,
                  message:
                    formData.type === 'WEBHOOK'
                      ? '路径不能为空'
                      : 'topic不能为空',
                  trigger: 'change',
                },
                {
                  pattern: formData.type === 'WEBHOOK' ? PATH_REG : TOPIC_REG,
                  message:
                    formData.type === 'WEBHOOK'
                      ? '请输入有效的路径'
                      : '请输入有效的topic',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                style="width: 100%"
                :maxlength="200"
                :placeholder="
                  formData.type === 'WEBHOOK'
                    ? '请输入路径，“/”开头'
                    : '请输入topic'
                "
                v-model.trim="config.value"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="colortheme" style="font-size: 26px">
              <i
                class="el-icon-circle-plus-outline poi ml15 hov"
                @click="addConfig(index)"
              ></i>
              <i
                v-if="formData.configJson.length > 1"
                class="el-icon-delete poi ml15 hov"
                @click="delConfig(index)"
              ></i>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { RULE_STATUS_ENUM } from "@/utils/enum"
import {
  COMMON_CODE_REG_64,
  COMMON_CODE_REG_64_MSG,
  TOPIC_REG,
} from "@/utils/reg"
import { postHmtrigger, putHmtrigger } from "@/apis/paas/HmTriggerController.js"
import { getHmhttprequestdefinitionPageList } from "@/apis/paas/HmHttpRequestDefinitionController.js"
import { getHmhttpservicePageList } from "@/apis/paas/HmHttpServiceController.js"
import { getHmmqttSelectlist } from "@/apis/paas/HmMqttLinkController.js"

import { cloneDeep } from "lodash"
const SERVICE_ENUM = [
  "insert",
  "update",
  "saveOrUpdate",
  "saveBatch",
  "updateBatch",
  "delete",
  "deleteBatch",
]
const PATH_REG = /^\/+/
export default {
  name: "TriggerForm",
  props: {
    modelInfo: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      RULE_STATUS_ENUM,
      COMMON_CODE_REG_64,
      COMMON_CODE_REG_64_MSG,
      PATH_REG,
      TOPIC_REG,
      loading: false,
      showVisible: false,
      serviceList: [],
      httpServiceList: [],
      mqttSelectList: [],
      web_configJson: [],
      mqtt_configJson: [],
      formData: {
        configJson: [{ key: null, value: "" }],
      },
    }
  },
  computed: {
    isNew() {
      return !this.formData.id
    },
  },
  methods: {
    async addForm() {
      this.showVisible = true
      const data = await getHmhttprequestdefinitionPageList({
        pageNo: 1,
        pageSize: 999999,
        modelId: this.modelInfo.id,
      })

      this.serviceList = data.data.filter(
        (i) =>
          (i.serviceType === "BUILT_IN" && SERVICE_ENUM.includes(i.key)) ||
          (i.serviceType === "SCRIPT" &&
            ["INSERT", "UPDATE", "DELETE"].includes(i.type))
      )
      this.loadHttpServiceList()
      this.loadMqttSelectList()
      this.web_configJson = [{ key: null, value: "" }]
      this.mqtt_configJson = [{ key: null, value: "" }]
      this.formData = {
        status: 1,
        type: "WEBHOOK",
        modelId: this.modelInfo.id,
        configJson: cloneDeep(this.web_configJson),
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async editForm(recordData = {}) {
      const record = cloneDeep(recordData)
      this.showVisible = true
      const data = await getHmhttprequestdefinitionPageList({
        pageNo: 1,
        pageSize: 999999,
        modelId: this.modelInfo.id,
      })
      this.serviceList = data.data.filter(
        (i) =>
          (i.serviceType === "BUILT_IN" && SERVICE_ENUM.includes(i.key)) ||
          (i.serviceType === "SCRIPT" &&
            ["INSERT", "UPDATE", "DELETE"].includes(i.type))
      )
      this.loadHttpServiceList()
      this.loadMqttSelectList()
      this.formData = {
        ...record,
        configJson: record.configJson || [{ key: null, value: "" }],
      }
      this.web_configJson =
        record.type === "WEBHOOK" && record.configJson
          ? cloneDeep(record.configJson)
          : [{ key: null, value: "" }]
      this.mqtt_configJson =
        record.type === "MQTT" && record.configJson
          ? cloneDeep(record.configJson)
          : [{ key: null, value: "" }]
      this.formData.services = record.services.map((i) => i.key) || []
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    loadHttpServiceList() {
      getHmhttpservicePageList({
        pageSize: 100000,
        pageNo: 1,
      }).then((res) => {
        this.httpServiceList = res.data
      })
    },
    loadMqttSelectList() {
      getHmmqttSelectlist().then((res) => {
        this.mqttSelectList = res
      })
    },
    changeType(val) {
      switch (val) {
        case "WEBHOOK":
          this.mqtt_configJson = cloneDeep(this.formData.configJson)
          this.formData.configJson = this.web_configJson
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
          !this.httpServiceList.length && this.loadHttpServiceList()
          break
        case "MQTT":
          this.web_configJson = cloneDeep(this.formData.configJson)
          this.formData.configJson = this.mqtt_configJson
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
          !this.mqttSelectList.length && this.loadMqttSelectList()
          break
        default:
          break
      }
    },
    addConfig(index) {
      this.formData.configJson.splice(index + 1, 0, {
        key: null,
        value: "",
      })
    },
    delConfig(index) {
      this.formData.configJson.splice(index, 1)
    },
    handleCancel() {
      this.showVisible = false
    },
    async submit() {
      try {
        await this.$refs.form.validate()
        let {
          id,
          code,
          modelId,
          name,
          notes,
          services,
          status,
          type,
          configJson,
        } = this.formData
        const strObj = {}
        for (let i = 0; i < configJson.length; i++) {
          if (strObj[`${configJson[i].key}_${configJson[i].value}`]) {
            this.$confirm(
              `${
                this.formData.type === "WEBHOOK" ? "回调地址" : "TOPIC主题"
              }不能重复`,
              "",
              {
                confirmButtonText: "关闭",
                showCancelButton: false,
                type: "warning",
              }
            )
            return
          }
          strObj[`${configJson[i].key}_${configJson[i].value}`] = true
        }
        let params = {}
        let request = null
        if (this.isNew) {
          params = {
            code,
            modelId,
            name,
            notes,
            status,
            type,
            configJson,
          }
          request = postHmtrigger
        } else {
          params = {
            id,
            code,
            modelId,
            name,
            notes,
            status,
            type,
            configJson,
          }
          request = putHmtrigger
        }
        params.services = this.serviceList.filter((i) =>
          services.includes(i.key)
        )
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key]
        }
        request(params).then((res) => {
          this.$message.success("操作成功")
          this.handleCancel()
          this.$emit("ok")
        })
      } catch (error) {
        console.log(error)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.hov:hover {
  opacity: 0.7;
}
</style>
